package com.cd.learn.cdlearn.resttemplate;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

/**
 * 本意是想用这个拦截请求动态向请求中添加动态的header值，结果没实现，现在这个类没用
 */
@Configuration
public class RestTemplateBeanPostProcess implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RestTemplate) {

            String o = TestContext.get();
            System.out.println("打印："+o);

            RestTemplate restTemplate = (RestTemplate) bean;
            restTemplate.setInterceptors(Collections.singletonList((request, body, execution) -> {
                HttpHeaders headers = request.getHeaders();
                headers.add("woqu", TestContext.get());
                return execution.execute(request, body);
            }));
            return restTemplate;
        }
        return bean;
    }
}
